var db = require('../config/mongo_database');
var jwt = require('jsonwebtoken');
var secret = require('../config/secret');
var redisClient = require('../config/redis_database').redisClient;
var tokenManager = require('../config/token_manager');

exports.signin = function(req, res) {
	var username = req.body.username || '';
	var password = req.body.password || '';
	console.log(username, password)
	// if(username != 'jinghaoran'){
	// 	return res.sendStatus(401); 
	// }

	db.userModel.findOne({username: username}, function (err, user) {
		console.log(user)
		if (err || null==user) {
			return res.sendStatus(401);
		}
		user.comparePassword(password, function(isMatch) {
			if (!isMatch) {
				return res.sendStatus(401);
            }
            var token = jwt.sign(user, secret.secretToken, {expiresIn: tokenManager.TOKEN_EXPIRATION }); //expiresIn: '24h'
            redisClient.set(token, '{is_expired:false}');
            redisClient.expire(token, tokenManager.TOKEN_EXPIRATION);
			return res.json({token:token});
		});

	});
};

// 获取注册用户列表
exports.list = function(req, res) {
	var pages = req.body.pages || 0;
	var user = tokenManager.getUser(req);
	if(user.username != 'jinghaoran'){
		return res.sendStatus(401); 
	}

	db.userModel.count({roletype:'0'}, function(err, count){
		console.log(err, count)
		db.userModel
		.where({roletype:'0'})
		.select({'username':1, 'email':1, 'score':1, 'grade':1})
		.skip(pages*12)
		.limit(12)
		.sort({ created : -1 })
		.exec(function(err, list){
			res.json({count:count, list:list});
		})
	});
};


exports.logout = function(req, res) {
	if (req.user) {
		tokenManager.expireToken(req.headers);

		delete req.user;	
		return res.sendStatus(200);
	}
	else {
		return res.sendStatus(401);
	}
}

